package offer.linkedList;

/**
 * @author DengYuan2
 * @create 2021-02-24 19:00
 */
public class n_35 {
    public static void main(String[] args) {
        n_35 n = new n_35();
        RandomListNode r1 = new RandomListNode(1);
        RandomListNode r2 = new RandomListNode(2);
        RandomListNode r3 = new RandomListNode(3);
        RandomListNode r4 = new RandomListNode(4);
        r1.next = r2;
        r2.next = r3;
        r3.next = r4;
        r1.random = r3;
        r2.random = r4;
        r3.random = r1;
        r4.random = r2;
        RandomListNode res = n.Clone(r1);
        System.out.println(res);
    }

    /**
     * 根据大神思路
     *
     * @param pHead
     * @return
     */
    public RandomListNode Clone(RandomListNode pHead) {
        if (pHead==null){
            return null;
        }
        RandomListNode cur = pHead;
        while (cur != null) {
            RandomListNode node = new RandomListNode(cur.label);
            node.next = cur.next;
            cur.next = node;
            cur = node.next;
        }
        cur = pHead;
        while (cur != null) {
            if (cur.random!=null){
                cur.next.random = cur.random.next;
            }
            cur = cur.next.next;
        }

        RandomListNode res=pHead.next;
        cur=pHead;
        while (cur.next!=null){
            RandomListNode tmp = cur.next;
            cur.next=tmp.next;
            cur=tmp;
        }
        return res;
    }
}
